package servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;

@WebServlet(name = "ReverseServlet", urlPatterns = "/ReverseServlet")
public class ReverseServlet extends HttpServlet {
    private static String message = "Error during Servlet processing";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            int len = request.getContentLength();
            if (len < 0) {
                response.setContentType("text/html;charset=utf-8");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().print("请求方式错误！");
                response.getWriter().close();
                return;
            }
            byte[] input = new byte[len];

            ServletInputStream sin = request.getInputStream();
            int c, count = 0;
            while ((c = sin.read(input, count, input.length - count)) != -1) {
                count += c;
            }
            sin.close();

            String inString = new String(input);
            int index = inString.indexOf("=");
            if (index == -1) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().print(message);
                response.getWriter().close();
                return;
            }
            String value = inString.substring(index + 1);

            //decode application/x-www-form-urlencoded string
            String decodedString = URLDecoder.decode(value, "UTF-8");

            //reverse the String
            String reverseStr = (new StringBuffer(decodedString)).reverse().toString();

            // set the response code and write the response data
            response.setStatus(HttpServletResponse.SC_OK);
            OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());

            writer.write(reverseStr);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            try {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().print(e.getMessage());
                response.getWriter().close();
            } catch (IOException ioe) {
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
